﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArtsShop.SharedUserControl;

namespace ArtsShop.Controls
{
    public partial class ProductFamilyImagesView : ProductFamilyControlView
    {
        #region Custom Events

       // public event ResetImageSelectors ResetImage;

        #endregion

        /// <summary>
        /// Gets or sets the productid of the control. If this is not null, show sku images
        /// </summary>
        /// <value>The product id.</value>
        public int? ProductId
        {
            get
            {
                if (ViewState["ProductFamilyImages.ProductId"] != null)
                {
                    return (int?)ViewState["ProductFamilyImages.ProductId"];
                }
                return null;
            }
            set
            {
                ViewState["ProductFamilyImages.ProductId"] = value;
            }
        }

        #region Page Events

        /// <summary>
        /// Renders the user control.
        /// </summary>
        public override void RenderUserControl()
        {
            if (!IsPostBack)
            {
                InitializeControl();
            }
        }

        #endregion

        #region Control Events

        /// <summary>
        /// Handles the ItemCommand event of the Repeater1 control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void ThumbnailImageRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (this.ProductId != null)
            {
                SetupImages(e.CommandArgument.ToString(), true);
            }
            else
            {
                SetupImages(e.CommandArgument.ToString(), false);
            }
        }

        /// <summary>
        /// Called when [change selector image].
        /// </summary>
        /// <param name="productId">The product id.</param>
        public void OnChangeSelectorImage(int productId)
        {
            // check if a product has been selected            
            //if (this._productFamily.SelectedProduct != null && this.ProductId != productId)
            //{
              //  this.ProductId = this._productFamily.SelectedProduct.ProductId;
                if (this.ProductId != null)
                {
                    InitializeControl();
                }
            //}
        }

        /// <summary>
        /// Handles the ItemDataBound event of the ThumbnailImageRepeater control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void ThumbnailImageRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ProductFamilyImage pfi = (ProductFamilyImage)e.Item.DataItem;

            if (pfi != null)
            {
                if (e.Item.FindControl("_thumbnailImage") != null)
                {
                    ImageButton button = (ImageButton)e.Item.FindControl("_thumbnailImage");

                    if (button != null)
                    {
                        button.ImageUrl = ImageUtility.BuildImageUrl(ImageDirectory.SmallImageFolderName, pfi.ImageUrl);
                    }
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the ResetMainImage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ResetMainImage_Click(object sender, EventArgs e)
        {
            this.ProductId = null;
            this._productFamily.SelectedProduct = null;

            if (ResetImage != null)
            {
                ResetImage();
                this.InitializeControl();
            }
        }

        #endregion


        #region Helper Methods

        /// <summary>
        /// Sets up the images.
        /// </summary>
        /// <param name="imageUrl">The image URL.</param>
        private void SetupImages(string imageUrl, bool isLinkVisible)
        {

            this._mainImage.ImageUrl = ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, imageUrl);
            this._mainImage.Attributes["onerror"] = "javascript:this.src='" + ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, "Image_placeholder.gif") + "'";

            if (_mainImageWithZoom != null)
            {
                this._mainImageWithZoom.ImageUrl = ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, imageUrl);
                this._mainImageWithZoom.Attributes["onerror"] = "javascript:this.src='" + ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, "Image_placeholder.gif") + "'";

                if (_zoomImageLink != null)
                {
                    string url = ImageUtility.BuildImageUrl(ImageDirectory.ZoomImageFolderName, imageUrl);

                    if (imageExists(url)) //If a zoom image exists on the server
                    {

                        this._zoomImageLink.NavigateUrl = url;
                        this._zoomImageLink.Visible = true;
                        this._mainImage.Visible = false;
                        this._zoomText.Visible = true;

                    }
                    else
                    {
                        this._zoomImageLink.Visible = false;
                        this._mainImage.Visible = true;
                        this._zoomText.Visible = false;
                    }

                    this._resetDefaultText.Visible = isLinkVisible;
                }
            }
        }

        /// <summary>
        /// Checks if image exists on server
        /// </summary>
        /// <param name="strURL">The STR URL.</param>
        /// <returns></returns>
        private bool imageExists(string strURL)
        {
            bool imageExists = true;
            try
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(strURL);
                System.Net.WebResponse res = req.GetResponse();
            }
            catch (Exception ex)
            {
                imageExists = false;
            }

            return imageExists;
        }

        /// <summary>
        /// Initializes the control.
        /// </summary>
        private void InitializeControl()
        {
            bool displayMainLink = false;
            this._mainImage.Attributes["onerror"] = "javascript:this.src='" + ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, "Image_placeholder.gif") + "'";
            if (_mainImageWithZoom != null)
            {
                this._mainImageWithZoom.Attributes["onerror"] = "javascript:this.src='" + ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, "Image_placeholder.gif") + "'";
            }

            // check if a product has been selected            
            if (this._productFamily.SelectedProduct != null)
            {
                this.ProductId = this._productFamily.SelectedProduct.ProductId;
            }


            ProductFamilyImage image = null;
            bool skuHasImages = true; // if false, use general productfamilyimages.

            // If in context of productfamily images (no productid available)
            if (ProductFamily != null && this.ProductId == null)
            {
                if (ProductFamily.ProductFamilyImages.Count > 0)
                {
                    // find the productfamily primary image
                    image = ProductFamily.ProductFamilyImages.Find(t => t.IsDefault);

                    if (image == null)
                    {
                        // no primary image, take first one
                        image = ProductFamily.ProductFamilyImages[0];
                    }
                }
                else
                {
                    // no general product family images, take random sku image
                    if (ProductFamily.ProductFamilySkuImages != null && ProductFamily.ProductFamilySkuImages.Count > 0)
                    {
                        image = ProductFamily.ProductFamilySkuImages[0];
                    }
                }
            }
            else if (ProductFamily != null && ProductId != null)
            {
                _resetDefaultText.Visible = true;

                // get the sku images
                List<ProductFamilyImage> skuimages = ProductFamily.ProductFamilySkuImages.FindAll(
                    delegate(ProductFamilyImage pfi)
                    {
                        return (this.ProductId == pfi.DiffProductId);
                    });

                // find the primary image for the current selected sku
                List<ProductFamilyImage> primaryskuimages = ProductFamily.ProductFamilySkuImages.FindAll(
                    delegate(ProductFamilyImage pfi)
                    {
                        return (pfi.DiffProductId == this.ProductId && pfi.IsDefault);
                    });

                if (displayMainLink = primaryskuimages.Count > 0)
                {
                    // if we have a primary sku image, setup that image
                    image = primaryskuimages.First();
                }
                else if (displayMainLink = skuimages.Count > 0)
                {
                    // if no primary sku image, but other sku images, set up random first one
                    image = skuimages.First();
                }
                else
                {
                    // no sku images, use the general productfamily images (if one or more exists)and set flag so as to 
                    // show general productfamily images in thumbnail container
                    if (ProductFamily.ProductFamilyImages.Count > 0)
                    {
                        image = ProductFamily.ProductFamilyImages.Find(t => t.IsDefault);
                        skuHasImages = false;
                        _resetDefaultText.Visible = false;
                    }
                }

                _resetDefaultText.Visible = displayMainLink;
            }

            // if we have an image, set up all images 
            if (image != null)
            {
                SetupImages(image.ImageUrl, displayMainLink);
            }
            else
            {
                this._mainImage.ImageUrl = ImageUtility.BuildImageUrl(ImageDirectory.LargeImageFolderName, "Image_placeholder.gif");
                this._zoomImageLink.Visible = false;
                this._mainImage.Visible = true;
                this._zoomText.Visible = false;

                this._resetDefaultText.Visible = true;
            }

            // set up the thumbnail image panel  - if no productId or the current selected product sku has no images use product family images
            if (this.ProductId == null || !skuHasImages)
            {
                // only take the first six images from the collection
                this.ThumbnailImageRepeater.DataSource = this._productFamily.ProductFamilyImages.Take(6);
            }
            else
            {
                // filter down to images for the current productid
                this.ThumbnailImageRepeater.DataSource = this._productFamily.ProductFamilySkuImages.FindAll(
                    delegate(ProductFamilyImage pfimage)
                    {
                        return (pfimage.DiffProductId == this.ProductId);

                    }).Take(6);
            }
            this.ThumbnailImageRepeater.DataBind();


            // hide the thumbnail container if no thumbnails
            bool hasMoreThanOneImage = this.ThumbnailImageRepeater.Items.Count > 1;
            if (_thumbnailImagesPanel != null)
            {
                _thumbnailImagesPanel.Visible = hasMoreThanOneImage;
            }
        }

        #endregion
       
    }
}